<template>
  <div class="department">
    <!-- 设备弹窗 -->
    <div class="dialog">
      <el-dialog
        :title="dialog.title"
        :visible.sync="dialog.visible"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
        :show-close="false"
      >
        <el-form
          class="form"
          :model="equipment"
          :rules="rules"
          label-position="right"
          label-width="100px"
          ref="form"
        >
          <el-form-item label="设备型号" prop="equipmentModelID">
            <el-select
              v-model="equipment.equipmentModelID"
              placeholder="请选择"
            >
              <el-option
                v-for="item in models"
                :key="item.key"
                :label="item.label"
                :value="item.key"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="上级位置" prop="parentID">
            <el-cascader
              v-model="spacesModel"
              :props="spaceProps"
              :options="options"
              clearable
              @change="selectChange"
            ></el-cascader>
          </el-form-item>
          <el-form-item label="设备名称" prop="name">
            <el-input v-model="equipment.name" />
          </el-form-item>
          <el-form-item label="报道间隔" prop="reportInterval">
            <el-input v-model="equipment.reportInterval" />
          </el-form-item>
          <el-form-item label="离线间隔" prop="offlineInterval">
            <el-input v-model="equipment.offlineInterval" />
          </el-form-item>
          <el-form-item label="串口号" prop="serialNumber">
            <el-input v-model="equipment.serialNumber" />
          </el-form-item>
          <el-form-item label="设备描述" prop="description">
            <el-input v-model="equipment.description" />
          </el-form-item>
          <el-form-item label="图片" prop="picture">
            <el-input v-model="equipment.picture" />
          </el-form-item>
          <el-form-item label="图片信息" prop="pictureMime">
            <el-input v-model="equipment.pictureMime" />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="cancelClick">取 消</el-button>
          <el-button type="primary" @click="confirmClick">确 定</el-button>
        </div>
      </el-dialog>
    </div>
    <!-- 权限弹窗 -->
    <div class="perm">
      <el-dialog
        :title="perm.title"
        :visible.sync="perm.visible"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
        :show-close="false"
      >
        <el-card>
          <el-form
            class="form"
            :model="detail"
            :rules="rules"
            label-position="right"
            ref="permform"
          >
            <el-form-item prop="id">
              <el-transfer
                :titles="['未关联群组', '已关联群组']"
                style="display: inline-block"
                v-model="detail.select"
                :data="groups"
                @right-check-change="handleRightChange"
              ></el-transfer>
            </el-form-item>
            <el-form-item prop="">
              <div v-for="(item, index) in permissions" :key="index">
                <span class="border">{{ item.label }} &nbsp; &nbsp;</span>
                <el-radio-group
                  v-model="item.hasPerm"
                  @change="handleRadioChange"
                >
                  <el-radio :label="1">允许</el-radio>
                  <el-radio :label="0">拒绝</el-radio>
                </el-radio-group>
              </div>
            </el-form-item>
          </el-form>
        </el-card>
        <div slot="footer" class="dialog-footer">
          <el-button @click="handleCancel">取 消</el-button>
          <el-button type="primary" @click="handleConfirm">确 定</el-button>
        </div>
      </el-dialog>
    </div>
    <div class="header">
      <el-form :inline="true" size="small" label-width="84px">
        <el-form-item label="设备名称">
          <el-input v-model="search.name" placeholder="" />
        </el-form-item>
        <el-form-item label="设备型号">
          <el-select v-model="search.modelID" placeholder="请选择" clearable>
            <el-option
              v-for="item in models"
              :key="item.key"
              :label="item.label"
              :value="item.key"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="设备位置">
          <el-cascader
              :props="spaceProps"
              :options="options"
              clearable
              @change="spaceChange">
          </el-cascader>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" size="mini" @click="getDatas(0, 9999)">查询</el-button>
          <el-button type="primary" size="mini" @click="addData">添加</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="content">
      <el-card>
        <el-table
          style="width: 100%"
          row-key="id"
          border
          :data="datas"
          :header-cell-style="{ 'background-color': '#EEEEEE' }"
        >
          <el-table-column prop="equipmentModelID" label="设备型号">
            <template slot-scope="scope">
              {{ getLabel(models, scope.row.equipmentModelID) }}
            </template>
          </el-table-column>
          <el-table-column prop="spaceID" label="设备位置">
            <template slot-scope="scope">
              {{ getLabel(spaces, scope.row.spaceID) }}
            </template>
          </el-table-column>
          <el-table-column prop="name" label="设备名称"></el-table-column>
          <el-table-column
            prop="reportInterval"
            label="报道间隔"
          ></el-table-column>
          <el-table-column
            prop="offlineInterval"
            label="离线间隔"
          ></el-table-column>
          <el-table-column prop="serialNumber" label="串口号"></el-table-column>
          <el-table-column
            prop="installDate"
            label="注册日期"
          ></el-table-column>
          <el-table-column
            prop="description"
            label="设备描述"
          ></el-table-column>
          <el-table-column prop="picture" label="图片"></el-table-column>
          <el-table-column
            prop="pictureMime"
            label="图片类型"
          ></el-table-column>
          <el-table-column prop="statusID" label="设备状态">
            <template slot-scope="scope">
              {{ statuses[scope.row.statusID].label }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200">
            <template slot-scope="scope">
              <el-button @click="showDialog(scope.row)" type="text" size="small">修改</el-button>
              <el-button @click="onDelete(scope.row)" type="text" size="small">删除</el-button>
              <el-button @click="handlePermission(scope.row)" type="text" size="small">设置权限</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="pagination">
          <el-pagination
            background
            @size-change="handleSizeChange"
            @current-change="handlePageChange"
            :total="total"
            :current-page.sync="pageNo"
            :page-sizes="[10, 20]"
            :page-size="10"
            layout="total, sizes, prev, pager, next"
          ></el-pagination>
        </div>
      </el-card>
    </div>
    <div class="footer"></div>
  </div>
</template>

<script>
import { getEquipments, addEquipment, updateEquipment, deleteEquipment, } from "@/api/equipment";
import { getEquipmentModels } from "@/api/equipment-model";
import { getSpaces } from "@/api/space";
import { getPermissions } from "@/api/permission";
import { getGroups } from "@/api/group";
import { setGroupPerm, getGroupPerm, getResourceDetail } from "@/api/group-permission";

export default {
  name: "equipment",
  data() {
    return {
      dialog: {
        title: "",
        visible: false,
        update: false,
      },
      perm: {
        title: "设置权限",
        visible: false,
      },
      statuses: [
        { key: 0, label: "停用" },
        { key: 1, label: "活动" },
        { key: 2, label: "草稿" },
        { key: 3, label: "审批中" },
        { key: 5, label: "由活动状态停用" },
        { key: 6, label: "由草稿状态停用" },
        { key: 7, label: "由审批状态停用" },
      ],
      pageNo: 1,
      pageSize: 10,
      total: 0,
      search: {
        name: "",
        spaceID: null,
        modelID: null,
      },
      spaces: [],
      models: [],
      datas: [],
      equipment: {
        id: null,
        equipmentID: null,
        spaceID: null,
        equipmentModelID: null,
        name: "",
        reportInterval: 0,
        offlineInterval: 0,
        serialNumber: null,
        installDate: null,
        description: null,
        picture: null,
        pictureMime: null,
        statusID: 1,
        employeeID_Update: this.$store.getters.uid,
      },
      permissions: [],
      groups: [],
      levels: [
        { key: 0, label: "无权限" },
        { key: 2, label: "查看数据" },
        { key: 4, label: "修改对象" },
        { key: 8, label: "修改下级对象" },
      ],
      detail: {
        select: [],
        id: null,
        groupid: null,
      },
      details: [],
      perms: [],
      rules: null,
      spacesModel: [],
      pNode: true,
      spaceProps: {
        lazy: false,
        checkStrictly: true
      },
    };
  },
  created() {
    const vm = this;
    vm.$nextTick(() => {
      vm.getDatas(vm.pageNo, vm.pageSize);
      getSpaces({
        name: vm.search.name,
        spaceID: vm.search.spaceID,
        modelID: vm.search.modelID,
        page: 0,
        size: 0,
      }).then((res) => {
        if (res.data instanceof Array) {
          for (let i = 0; i < res.data.length; i++) {
            let d = res.data[i];
            vm.spaces.push({ key: d.spaceID, label: d.name });
          }
        }
      });
      getEquipmentModels({ page: 0, size: 0 }).then((res) => {
        if (res.data instanceof Array) {
          for (let i = 0; i < res.data.length; i++) {
            let d = res.data[i];
            vm.models.push({ key: d.equipmentModelID, label: d.name });
          }
        }
      });
      getPermissions({ page: 0, size: 0 })
        .then((res) => {
          for (let i = 0; i < res.data.length; i++) {
            let d = res.data[i];
            vm.permissions.push({ key: d.id, label: d.name, hasPerm: 1 });
          }
          Promise.resolve();
        })
        .catch((err) => {
          Promise.reject();
        });
      getGroups({ page: 0, size: 0 })
        .then((res) => {
          for (let i = 0; i < res.data.length; i++) {
            let d = res.data[i];
            vm.groups.push({ key: d.id, label: d.name });
          }
          Promise.resolve();
        })
        .catch((err) => {
          Promise.reject();
        });
    });
  },
  computed: {
    options() {
      return this.$store.state.space.options
    },
  },
  mounted() {
    this.$store.dispatch('space/GetSpaces', { name: '', parentid: '', page: 0, size: 0 })
  },
  destroyed() {},
  methods: {
    getDatas(pageNo, pageSize) {
      const vm = this;
      getEquipments({
        page: pageNo, 
        size: pageSize, 
        spaceId: this.search.spaceID,
        modelId: this.search.modelID
        })
        .then((res) => {
          vm.datas = res.data;
          vm.total = res.data.length;
          Promise.resolve();
        })
        .catch((err) => {
          Promise.reject(err);
        });
    },
    addData() {
      const vm = this;
      vm.dialog.title = "添加设备";
      vm.dialog.visible = true;
      vm.dialog.update = false;
      vm.equipment = {
        id: null,
        equipmentID: null,
        spaceID: null,
        equipmentModelID: null,
        name: "",
        reportInterval: 0,
        offlineInterval: 0,
        serialNumber: null,
        installDate: null,
        description: null,
        picture: null,
        pictureMime: null,
        statusID: 1,
        employeeID_Update: this.$store.getters.uid,
      };
    },
    showDialog(row) {
      const vm = this;
      vm.dialog.title = "修改设备";
      vm.dialog.visible = true;
      vm.dialog.update = true;
      this.spacesModel = this.getModel(row.spaceID);
      vm.equipment = {
        id: row.id,
        equipmentID: row.equipmentID,
        spaceID: row.spaceID,
        equipmentModelID: row.equipmentModelID,
        name: row.name,
        reportInterval: row.reportInterval,
        offlineInterval: row.offlineInterval,
        serialNumber: row.serialNumber,
        installDate: row.installDate,
        description: row.description,
        picture: row.picture,
        pictureMime: row.pictureMime,
        statusID: row.statusID,
      };
    },
    onDelete(row) {
      const vm = this;
      vm.$confirm("是否删除?", "提示信息", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then((action) => {
        if (action === "confirm") {
          deleteEquipment({ ids: row.equipmentID })
            .then((res) => {
              vm.$message({
                message: res.message,
                type: "success",
              });
              Promise.resolve();
              vm.getDatas(vm.pageNo, vm.pageSize);
            })
            .catch((err) => {
              Promise.resolve();
            });
        }
      });
    },
    handleRightChange(old_keys, new_keys) {
      const vm = this;
      if (new_keys && new_keys.length > 0) {
        vm.detail.groupid = new_keys[new_keys.length - 1];
      }
      vm.permissions.forEach((ele) => {
        ele.hasPerm = 1;
      });
      vm.details.forEach((element) => {
        if (element.id == vm.detail.groupid) {
          vm.permissions.forEach((ele) => {
            element.pdList.forEach((e) => {
              if (ele.key == e.permissionID) {
                ele.hasPerm = e.allowPermission;
              }
              let index = vm.perms.findIndex(
                p => p.groupID == e.groupID && p.permissionID == e.permissionID
              );
              if (index == -1) {
                vm.perms.push(e);
              }
            });
          });
        }
      });
      vm.permissions.forEach((ele) => {
        let perm = {
          id: 0,
          permissionID: ele.key,
          groupID: vm.detail.groupid,
          resourceID: vm.detail.id,
          allowPermission: ele.hasPerm ? 1 : 0,
          denyPermission: ele.hasPerm ? 0 : 1,
          statusID: 1,
          employeeID_Update: vm.$store.getters.uid,
        };
        let index = vm.perms.findIndex(
          p => p.groupID == perm.groupID && p.permissionID == perm.permissionID
        );
        if (index == -1) {
          vm.perms.push(perm);
        }
      });
    },
    handleRadioChange(val) {
      const vm = this;
      if (vm.permissions && vm.permissions.length > 0) {
        vm.permissions.forEach((e) => {
          let perm = {
            id: 0,
            permissionID: e.key,
            groupID: vm.detail.groupid,
            resourceID: vm.detail.id,
            allowPermission: e.hasPerm ? 1 : 0,
            denyPermission: e.hasPerm ? 0 : 1,
            statusID: 1,
            employeeID_Update: vm.$store.getters.uid,
          };
          let has = false;
          for (let i = 0; i < vm.perms.length; i++) {
            if (
              vm.perms[i].groupID == perm.groupID &&
              vm.perms[i].permissionID == perm.permissionID
            ) {
              vm.perms[i].allowPermission = perm.allowPermission;
              vm.perms[i].denyPermission = perm.denyPermission;
              has = true;
              break;
            }
          }
          if (!has && vm.detail.groupid) {
            vm.perms.push(perm);
          }
        });
      }
    },
    handlePermission(row) {
      const vm = this;
      vm.perm.visible = true;
      vm.detail.id = row.equipmentID;
      vm.detail.groupid = null;
      vm.perms = [];
      getResourceDetail({ id: vm.detail.id }).then((res) => {
        vm.details = [];
        vm.detail.select = [];
        if (res.data && res.data instanceof Array) {
          vm.details = res.data;
          res.data.forEach((e) => {
            if (e.id) {
              vm.detail.select.push(e.id);
            }
          });
        }
      });
      vm.permissions.forEach((ele) => {
        ele.hasPerm = 1;
      });
    },
    handleCancel() {
      this.perm.visible = false;
    },
    handleConfirm() {
      const vm = this;
      // setGroupPerm({ data: JSON.stringify(vm.perms) }).then((res) => {
      //   vm.perm.visible = false;
      //   vm.$message({
      //     message: res.message,
      //     type: "success",
      //   });
      //   Promise.resolve();
      // });
    },
    cancelClick() {
      const vm = this;
      vm.dialog.visible = false;
    },
    confirmClick() {
      const vm = this;
      if (!vm.dialog.update) {
        addEquipment(vm.equipment).then((res) => {
          vm.dialog.visible = false;
          vm.$message({
            message: res.message,
            type: "success",
          });
          Promise.resolve();
          vm.getDatas(vm.pageNo, vm.pageSize);
        });
      } else {
        updateEquipment(vm.equipment).then((res) => {
          vm.dialog.visible = false;
          vm.$message({
            message: res.message,
            type: "success",
          });
          Promise.resolve();
          vm.getDatas(vm.pageNo, vm.pageSize);
        });
      }
    },
    handleSizeChange(val) {
      const vm = this;
      vm.pageSize = val;
    },
    handlePageChange(val) {
      const vm = this;
      vm.pageNo = val;
      vm.getDatas(vm.pageNo, vm.pageSize);
    },
    //上级位置
    selectChange(val) {
      if (val.length > 0) {
        this.equipment.spaceID = val[val.length - 1];
      }
    },
    spaceChange(val) {
      if (val.length > 0) {
        this.search.spaceID = val[val.length - 1];
      } else {
        this.search.spaceID = null;
      }
    },
    getLabel(arr, id) {
      if (arr && arr.length > 0) {
        for (let i = 0; i < arr.length ;i++) {
          if (arr[i].key == id) {
            return arr[i].label
          }
        }
      }
      return ""
    },
    getModel(id) {
      let model = [];
      let isFind = 0;
      const func = (id, arr, h) => {
        arr.forEach(e => {
          if (isFind) {
            return;
          }
          while (model.length > h) {
            model.pop();
          }
          if (e.value == id) {
            isFind = 1;
            model.push(e.value);
            return model;
          } else if (e.children) {
            model.push(e.value);
            func(id, e.children, h + 1);
          }
        })
      }
      func(id, this.options, 0);
      return model;
    }
  },
};
</script>

<style lang="scss" scoped>
.department {
  width: 100%;
  padding: 30px;
  .header {
    margin-bottom: 20px;
  }
  .content {
    margin-bottom: 20px;
  }
  .pagination {
    margin-top: 20px;
  }
  .border {
    border-radius: 6px;
    box-shadow: 0 0 6px lightgray;
    padding: 5px 10px;
    margin: 0 20px 0 0;
  }
}
</style>